package com.jp.knowledge.my.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.ImagePickerIntent;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.ClipImageActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.http.HttpGet;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.UserSettingCompanysAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.model.SettingUserDataModel;
import com.jp.knowledge.my.model.SettingWeChatModel;
import com.jp.knowledge.service.SaveUserDataService;
import com.jp.knowledge.util.HeadIconUploader;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.MultipleImageUploader;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.ClipViewLayout;
import com.jp.knowledge.view.FlowLayout;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.JpRecycleView;
import com.jp.knowledge.wxapi.WXEntryActivity;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by 528787067@qq.com on 2017/2/13.
 */

public class UserSettingActivity extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener, MultipleImageUploader.ImageUploadCallBack, HttpGet.HttpGetCallback {

    private static final int SELECT_HEAD_IMG_CODE = 0x01;
    private static final int ORGANIZE_SETTING_CODE = 0x02;
    private static final int DEPARTMENT_SETTING_CODE = 0x03;
    private static final int COMPANY_SETTING_CODE = 0x04;
    private static final int COMPANY_DEP_POSI_SETTING_CODE = 0x05;
    private static final int UPDATE_USER_INFO = 0x06;
    private static final int REQUEST_CROP_PHOTO = 0x07;

    private SettingUserDataModel settingUserDataModel;
    private UserData userData;
    private PersonLogic personLogic;
    private HeadIconUploader headIconUploader;
    private List<OrganizaModel> companysData;
    private UserSettingCompanysAdapter companysAdapter;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    @ViewInject(R.id.user_setting_item_head)
    private LinearLayout headItem;
    @ViewInject(R.id.user_setting_item_head_icon)
    private ImageView headIcon;
    @ViewInject(R.id.user_setting_item_nickname)
    private LinearLayout nicknameItem;
    @ViewInject(R.id.user_setting_item_nickname_desc)
    private TextView nicknameDesc;
    @ViewInject(R.id.user_setting_item_username)
    private LinearLayout userNameItem;
    @ViewInject(R.id.user_setting_item_username_desc)
    private TextView userNameDesc;
    @ViewInject(R.id.user_setting_item_username_icon)
    private ImageView userNameIcon;
    @ViewInject(R.id.user_setting_item_phone)
    private LinearLayout phoneNumItem;
    @ViewInject(R.id.user_setting_item_phone_desc)
    private TextView phoneNumDesc;
    @ViewInject(R.id.user_setting_item_sex)
    private LinearLayout sexItem;
    @ViewInject(R.id.user_setting_item_sex_desc)
    private TextView sexDesc;
    @ViewInject(R.id.user_setting_item_organize)
    private LinearLayout organizeItem;
    @ViewInject(R.id.user_setting_item_organize_desc)
    private TextView organizeDesc;
    @ViewInject(R.id.user_setting_item_department)
    private LinearLayout departmentItem;
    @ViewInject(R.id.user_setting_item_department_desc)
    private TextView departmentDesc;
    @ViewInject(R.id.user_setting_item_position)
    private LinearLayout positionItem;
    @ViewInject(R.id.user_setting_item_position_desc)
    private TextView positionDesc;
    @ViewInject(R.id.user_setting_item_mail)
    private LinearLayout mailItem;
    @ViewInject(R.id.user_setting_item_mail_desc)
    private TextView mailDesc;
    @ViewInject(R.id.user_setting_item_skill)
    private LinearLayout skillItem;
    @ViewInject(R.id.user_setting_item_skill_desc)
    private TextView skillDesc;
    @ViewInject(R.id.user_setting_icon_companys)
    private ImageView companysAddIcon;
    @ViewInject(R.id.user_setting_companys_view)
    private JpRecycleView companysView;
    @ViewInject(R.id.user_setting_icon_industry)
    private ImageView industryAddIcon;
    @ViewInject(R.id.user_setting_industry_view)
    private FlowLayout industryView;
    @ViewInject(R.id.wechat_had_bind)
    private TextView weChatHadView;
    @ViewInject(R.id.bind_wechat_lly)
    private LinearLayout bindWeChatView;
    @ViewInject(R.id.bind_wechat_remind_tv)
    private TextView bindWeChatRemindText;
    @ViewInject(R.id.bind_wechat_tv)
    private TextView bindWeChatText;

    private CommDialog saveDialog;
    private CommDialog clearCacheDialog;
    private SelectDialog sexSelectDialog;
    private SelectDialog skillLevelSelectDialog;

    @Override
    protected int getResourceId() {
        return R.layout.activity_set_user_data;
    }

    @Override
    protected void init() {
        userData = application.getUserData();
        personLogic = new PersonLogic(this);
        settingUserDataModel = new SettingUserDataModel(userData);
        companysData = new ArrayList<>();
        if(userData != null && userData.getCompanyList() != null)
            companysData.addAll(userData.getCompanyList());
        headIconUploader = new HeadIconUploader(this);
        headIconUploader.setImageUploadCallBack(this);
        initTitleBar();
        initDialog();
        initDesc();
        initComppanysView();
        initSkillsView();
        initOtherView();
        initClickListener();
        initBroadcase();
    }

    private void initTitleBar(){
        topName.setText(R.string.my_tv_file);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setText("保存");
        rightBtn.setVisibility(View.GONE);
    }

    private void initDialog(){
        saveDialog = new CommDialog(this);
        saveDialog.setContent("用户信息已发生改变，是否先保存在离开？");
        saveDialog.setLeft("离开");
        saveDialog.setRight("保存");
        saveDialog.setRightListener(this);
        saveDialog.setLeftListener(this);

        sexSelectDialog = new SelectDialog(this);
        sexSelectDialog.setTitle("选择性别");
        sexSelectDialog.addItem("男");
        sexSelectDialog.addItem("女");
        sexSelectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
            @Override
            public void onSelectItemClick(int position) {
                settingUserDataModel.setGender((position==0) ? "男" : "女");
                sexDesc.setText(settingUserDataModel.getGender());
            }
        });

        skillLevelSelectDialog = new SelectDialog(this);
        skillLevelSelectDialog.setTitle("选择等级");
        skillLevelSelectDialog.addItem("初级");
        skillLevelSelectDialog.addItem("中级");
        skillLevelSelectDialog.addItem("高级");
        skillLevelSelectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
            @Override
            public void onSelectItemClick(int position) {
                settingUserDataModel.setSkillLevel(position+1);
                setDestToTextView(settingUserDataModel.getSkillText(), skillDesc);
            }
        });
    }

    private void initDesc(){
        setDestToTextView(settingUserDataModel.getNickname(), nicknameDesc);
        setDestToTextView(settingUserDataModel.getUsername(), userNameDesc);
        setDestToTextView(userData.getPhone(), phoneNumDesc);
        setDestToTextView(settingUserDataModel.getGender(), sexDesc);
        setDestToTextView(settingUserDataModel.getCompanyName(), organizeDesc);
        setDestToTextView(settingUserDataModel.getDepartmentName(), departmentDesc);
        setDestToTextView(settingUserDataModel.getPosition(), positionDesc);
        setDestToTextView(settingUserDataModel.getEmail(), mailDesc);
        setDestToTextView(settingUserDataModel.getSkillText(), skillDesc);
    }

    private void initComppanysView(){
        companysView.setHasFixedSize(true);
        companysView.addItemDecoration(new JpDiver(this));
        companysView.setLayoutManager(new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        companysAdapter = new UserSettingCompanysAdapter(this, companysData);
        companysView.setAdapter(companysAdapter);
        companysAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                startActivityForResult(new Intent(mContext, UserSettingEditCompany.class)
                        .putExtra("data", companysData.get(position)), COMPANY_DEP_POSI_SETTING_CODE);
            }
        });
    }

    private void initSkillsView(){
        industryView.removeAllViews();
        for(UserData.SkillsBean skillsBean : settingUserDataModel.getSkills()) {
            TextView textView = new TextView(this);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.min_font));
            textView.setGravity(Gravity.CENTER);
            textView.setText(skillsBean.getSkillName());
            textView.setTextColor(getResources().getColor(R.color.font_gray_deep));
            textView.setBackground(getResources().getDrawable(R.drawable.btn_rbg_gray));
            textView.setPadding((int)(getResources().getDimension(R.dimen.space_middle)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_min)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_middle)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_min)+0.5));
            industryView.addView(textView);
        }
    }

    private void initOtherView(){
        ImageLoadUtil.loadCircle(this, settingUserDataModel.getPortrait(), headIcon);
        industryAddIcon.setBackgroundColor(getResources().getColor(R.color.white));
        setOrganizeVisibility();
//        if(userData.getBindWeixin() != 1) {
//            weChatHadView.setVisibility(View.GONE);
//            bindWeChatView.setVisibility(View.VISIBLE);
//        } else {
//            bindWeChatView.setVisibility(View.GONE);
////            weChatHadView.setVisibility(View.VISIBLE);
//            weChatHadView.setVisibility(View.GONE);
//        }
        if(userData.getBindWeixin() != 1) {
            bindWeChatRemindText.setText("绑定微信可以直接获取头像、昵称\t");
            bindWeChatText.setText("绑定微信");
        } else{
            bindWeChatRemindText.setText("已绑定微信\t");
            bindWeChatText.setText("重新绑定");
        }
        userNameIcon.setVisibility(TextUtils.isEmpty(userData.getUpdateName()) ? View.VISIBLE : View.INVISIBLE);
        skillItem.setVisibility(View.GONE);
    }

    private void initClickListener(){
        leftIcon.setOnClickListener(this);
        rightBtn.setOnClickListener(this);
        headItem.setOnClickListener(this);
        nicknameItem.setOnClickListener(this);
        userNameItem.setOnClickListener(this);
        phoneNumItem.setOnClickListener(this);
        sexItem.setOnClickListener(this);
        organizeItem.setOnClickListener(this);
        departmentItem.setOnClickListener(this);
        positionItem.setOnClickListener(this);
        companysAddIcon.setOnClickListener(this);
        mailItem.setOnClickListener(this);
        skillItem.setOnClickListener(this);
        industryAddIcon.setOnClickListener(this);
        bindWeChatText.setOnClickListener(this);
    }

    private void initBroadcase(){
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.COMPANY_JOIN.equals(action)){
                    OrganizaModel organizaModel = (OrganizaModel) intent.getSerializableExtra("joinCompany");
                    int index = intent.getIntExtra("index", 0);
                    if(organizaModel == null)
                        return;
                    companysData.add(index, organizaModel);
                    companysAdapter.updateAdapter(companysData);
                } else if(LocalBroadCast.COMPANY_EXIT.equals(action)){
                    String companyId =  intent.getStringExtra("companyId");
                    if(companyId == null)
                        return;
                    for(int i = 0, j = companysData.size(); i < j; i++){
                        if(companyId.equals(companysData.get(i).getCompanyId())){
                            companysAdapter.removeData(i);
                            return;
                        }
                    }
                } else if(LocalBroadCast.COMPANY_SORT.equals(action)){
                    List<String> companyIds = intent.getStringArrayListExtra("companyIds");
                    List<OrganizaModel> companyModels = new ArrayList<>();
                    for(String companyId : companyIds){
                        for(OrganizaModel companyModel: companysData){
                            if(companyId.equals(companyModel.getCompanyId())){
                                companyModels.add(companyModel);
                                break;
                            }
                        }
                    }
                    companysData.clear();
                    companysData.addAll(companyModels);
                    companysAdapter.updateAdapter(companysData);
                } else if(LocalBroadCast.PHONE_REBIND_CODE.equals(action)){
                    String phone = intent.getStringExtra("phone");
                    if(phone != null) {
                        userData.setPhone(phone);
                        setDestToTextView(userData.getPhone(), phoneNumDesc);
                    }
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.COMPANY_JOIN);
        intentFilter.addAction(LocalBroadCast.COMPANY_EXIT);
        intentFilter.addAction(LocalBroadCast.COMPANY_SORT);
        intentFilter.addAction(LocalBroadCast.PHONE_REBIND_CODE);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == MoreRoleActivity.ROLE_RESULT_CODE // 我的标签
                && resultCode == MoreRoleActivity.INDUSTRY_RESULT_CODE) {
            if(data == null)
                settingUserDataModel.setSkills(null);
            else
                settingUserDataModel.setSkills((List<UserData.SkillsBean>) data.getSerializableExtra("role"));
            initSkillsView();
            return;
        } else if(resultCode != RESULT_OK || data == null) {
            return;
        }
        if(requestCode == SELECT_HEAD_IMG_CODE){            // 选择头像
            List<String> imageSelectedPaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
            if(imageSelectedPaths == null && imageSelectedPaths.size() == 0)
                return;
            Uri uri = Uri.parse(imageSelectedPaths.get(0));
            gotoClipActivity(uri, 2);
//            settingUserDataModel.setPortrait(imageSelectedPaths.get(0));
//            ImageLoadUtil.loadCircle(this, settingUserDataModel.getPortrait(), headIcon);
        } else if(requestCode == REQUEST_CROP_PHOTO){       // 剪切图片
            Uri uri = data.getData();
            if (uri == null)
                return;
            settingUserDataModel.setPortrait(ClipViewLayout.getRealFilePathFromUri(mContext, uri));
            ImageLoadUtil.loadCircle(this, settingUserDataModel.getPortrait(), headIcon);
        } else if(requestCode == UserSettingEditActivity.REQUEST_CODE) {
            String resultData = data.getStringExtra(UserSettingEditActivity.RESULT_DATA);
            switch (data.getIntExtra(UserSettingEditActivity.VIEW_ID, 0x00)) {
                case R.id.user_setting_item_nickname:       // 昵称
                    settingUserDataModel.setNickname(resultData);
                    setDestToTextView(settingUserDataModel.getNickname(), nicknameDesc);
                    break;
                case R.id.user_setting_item_username:       // 姓名
                    userData.setUpdateName(resultData);
                    userNameIcon.setVisibility(View.INVISIBLE);
                    settingUserDataModel.setUsername(resultData);
                    setDestToTextView(settingUserDataModel.getUsername(), userNameDesc);
                    break;
                case R.id.user_setting_item_position:       // 职位
                    settingUserDataModel.setPosition(resultData);
                    setDestToTextView(settingUserDataModel.getPosition(), positionDesc);
                    break;
                case R.id.user_setting_item_mail:      // 邮箱
                    settingUserDataModel.setEmail(resultData);
                    setDestToTextView(settingUserDataModel.getEmail(), mailDesc);
                    break;
            }
        } else if(requestCode == ORGANIZE_SETTING_CODE){    // 组织
            settingUserDataModel.setCompanyName(userData.getCompanyName());
            setDestToTextView(settingUserDataModel.getCompanyName(), organizeDesc);
            setOrganizeVisibility();
        } else if(requestCode == DEPARTMENT_SETTING_CODE){  // 部门
            settingUserDataModel.setDepartmentId(data.getStringExtra(UserSettingDepartmentActivity.SELECTED_DEPARTMENT_ID));
            settingUserDataModel.setDepartmentName(data.getStringExtra(UserSettingDepartmentActivity.SELECTED_DEPARTMENT_NAME));
            setDestToTextView(settingUserDataModel.getDepartmentName(), departmentDesc);
            setOrganizeVisibility();
        } else if(requestCode == COMPANY_SETTING_CODE){     // 组织管理

        } else if(requestCode == COMPANY_DEP_POSI_SETTING_CODE){ // 编辑组织部门职位
            OrganizaModel organizaModel = (OrganizaModel) data.getSerializableExtra("data");
            if(organizaModel == null)
                return;
            for(int i = 0, j = companysData.size(); i < j; i++){
                OrganizaModel model = companysData.get(i);
                if(model.getCompanyId().equals(organizaModel.getCompanyId())){
                    model.setDepartment(organizaModel.getDepartment());
                    model.setDepartmentId(organizaModel.getDepartmentId());
                    model.setPosition(organizaModel.getPosition());
                    companysAdapter.notifyItemChanged(i);
                    return;
                }
            }
        }
    }

    /* 选择头像 */
    private void gotoSelectHeadIcon(){
        ImagePickerIntent intent = new ImagePickerIntent(this);
        intent.setSelectModel(SelectModel.MULTI);
        intent.setMaxTotal(1);
        intent.setShowCarema(true);
        startActivityForResult(intent, SELECT_HEAD_IMG_CODE);
        overridePendingTransition(R.anim.anim_enter, 0);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.icon_left:                          // 返回
//                if(settingUserDataModel.hasDataChange(userData))
//                    saveDialog.show();
//                else
                    finish();
                break;
            case R.id.right_bn:                           // 保存
//                if(settingUserDataModel.hasDataChange(userData))
//                    saveUserData();
//                else
                    finish();
                break;
            case R.id.user_setting_item_head:           // 头像设置
                gotoSelectHeadIcon();
                break;
            case R.id.user_setting_item_nickname:       // 昵称设置
                UserSettingEditActivity.gotoEdit(this, R.id.user_setting_item_nickname,
                        "设置昵称", settingUserDataModel.getNickname(), "输入你的昵称");
                break;
            case R.id.user_setting_item_username:       // 用户名设置
                if(TextUtils.isEmpty(userData.getUpdateName())) {
                    UserSettingEditActivity.gotoEdit(this, R.id.user_setting_item_username,
                            "设置姓名", settingUserDataModel.getUsername(), "输入你的姓名",
                            UserSettingEditActivity.TYPE_NAME);
                }
                break;
            case R.id.user_setting_item_phone:          // 手机号码
                startActivity(new Intent(mContext, BindPhoneActivity.class));
                break;
            case R.id.user_setting_item_sex:            // 性别设置
                sexSelectDialog.show();
                break;
            case R.id.user_setting_item_organize:       // 组织设置
                startActivityForResult(new Intent(mContext, OrganizeActivity.class), ORGANIZE_SETTING_CODE);
                break;
            case R.id.user_setting_item_department:     // 部门设置
                startActivityForResult(new Intent(mContext, UserSettingDepartmentActivity.class), DEPARTMENT_SETTING_CODE);
                break;
            case R.id.user_setting_item_position:       // 职位设置
                UserSettingEditActivity.gotoEdit(this, R.id.user_setting_item_position,
                        "设置职位", settingUserDataModel.getPosition(), "输入你所在的职位");
                break;
            case R.id.user_setting_item_mail:      // 邮箱
                UserSettingEditActivity.gotoEdit(this, R.id.user_setting_item_mail,
                        "设置邮箱", settingUserDataModel.getEmail(), "输入邮箱",
                        UserSettingEditActivity.TYPE_MAIL);
                break;
            case R.id.user_setting_item_skill:      // 技能级别
                skillLevelSelectDialog.show();
                break;
            case R.id.user_setting_icon_companys:       // 所属组织
                startActivityForResult(new Intent(this, OrganizeActivity.class), COMPANY_SETTING_CODE);
                break;
            case R.id.user_setting_icon_industry:       // 关注行业
                Intent intent = new Intent(this, MoreRoleActivity.class);
                intent.putExtra("skill", true);
                intent.putExtra("skilles", (Serializable) settingUserDataModel.getSkills());
                startActivityForResult(intent, MoreRoleActivity.ROLE_RESULT_CODE);
                break;
            case R.id.left_btn:
                finish();
                break;
            case R.id.right_btn:
                onClick(rightBtn);
                break;
            case R.id.bind_wechat_tv:
                bindWeChat();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        onClick(leftIcon);
    }

    /* 保存用户数据 */
    private void saveUserData(){
//        if(settingUserDataModel.getNickname() == null || settingUserDataModel.getNickname().trim().length() == 0){
//            ToasUtil.toast(this, "昵称必填，对外公开显示");
//        } else if(settingUserDataModel.getUsername() == null || settingUserDataModel.getUsername().trim().length() == 0){
//            ToasUtil.toast(this, "姓名必填，团队圈内部显示");
//        }else if(settingUserDataModel.getPortrait() != null
//                && !settingUserDataModel.getPortrait().equals(userData.getPortrait())){
//            headIconUploader.addImage(settingUserDataModel.getPortrait());
//            headIconUploader.uploadImages();
//        } else {
//            commitData();
//        }
        // 将数据提交扔给 Service 去处理
        startService(new Intent(this, SaveUserDataService.class)
                .putExtra(SaveUserDataService.SETTING_USER_DATA_MODEL, settingUserDataModel));
    }

    /* 提交用户数据 */
    private void commitData(){
        JsonObject param = settingUserDataModel.toJsonObject(userData);
        if(param == null){
            ToasUtil.toast(this, "抱歉，数据出错，请稍后重试");
        } else{
            HttpHelper.getInstance(this).updateUserInfo(param, UPDATE_USER_INFO, this);
        }
    }

    private void setOrganizeVisibility(){
        if(settingUserDataModel.getCompanyName() == null
                || settingUserDataModel.getCompanyName().trim().length() == 0){
            departmentItem.setVisibility(View.GONE);
            positionItem.setVisibility(View.GONE);
            return;
        }
        departmentItem.setVisibility(View.VISIBLE);
        if(settingUserDataModel.getDepartmentName() == null
                || settingUserDataModel.getDepartmentName().trim().length() == 0){
            positionItem.setVisibility(View.GONE);
            return;
        }
        positionItem.setVisibility(View.VISIBLE);
    }

    private void setDestToTextView(String desc, TextView destTextView){
        if(desc == null || desc.trim().length() == 0)
            destTextView.setText("未设置");
        else
            destTextView.setText(desc);
    }

    /* 剪切图片 */
    public void gotoClipActivity(Uri uri, int type) {
        if (uri == null)
            return;
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", type);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    /* 数据提交回调 */
    @Override
    public void onStart(int requestType) {
        loading.show();
    }
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }
    @Override
    public void onError(int requestType) {
        ToasUtil.toast(this, "抱歉，数据提交失败，请稍后重试");
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0) {
            onError(requestType);
            return;
        }
        if(requestType == UPDATE_USER_INFO) {
//            ToasUtil.toast(this, "保存成功");
            personLogic.getUserData();
//            super.finish();
        } else if(requestType == WEICHAT_DATA_COMMIT_CODE){
            ToasUtil.toast(this, "微信绑定成功");
        }
    }

    /* 头像上传回调 */
    @Override
    public void imageCompressFail(String key) {
        ToasUtil.toast(this, "抱歉，头像压缩失败");
        imageUploadSuccess(key, userData.getPortrait());
    }
    @Override
    public void imageCompressSuccess(String key) {}
    @Override
    public void imageCompressComplete() {}
    @Override
    public void imageUploadFail(String key) {
        ToasUtil.toast(this, "抱歉，头像上传失败");
        imageUploadSuccess(key, userData.getPortrait());
    }
    @Override
    public void imageUploadSuccess(String key, String resultKey) {
        settingUserDataModel.setPortrait(resultKey);
        commitData();
    }
    @Override
    public void imageUploadComplete(List<String> resultKeys) {}


    /* 以下是绑定微信相关操作 */

    private static final int WEICHAT_ACCESS_TOKEN_CODE = 0x05;  //微信绑定获取 access_token
    private static final int WEICHAT_GET_USER_DATA = 0x06;      //微信绑定获取个人信息
    private static final int WEICHAT_DATA_COMMIT_CODE = 0x07;   // 提交微信绑定信息

    private IWXAPI api;
    private BroadcastReceiver weChatBroadcaseReciver;
    private LocalBroadcastManager weChatLocalBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initIWXAPI();
        initWeChatBroadcastReceiver();
    }

    /* 初始化微信绑定 api */
    private void initIWXAPI(){
        api = WXAPIFactory.createWXAPI(this, "wx73bea73b9ead58e8", true);
        api.registerApp("wx73bea73b9ead58e8");
    }

    /* 初始化微信接收广播 */
    private void initWeChatBroadcastReceiver(){
        weChatLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        weChatBroadcaseReciver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction() != WXEntryActivity.WECHAT_BIND)
                    return;
                int errCode = intent.getIntExtra(WXEntryActivity.WECHAT_BIND_ERR_CODE, -1);
                if(errCode == BaseResp.ErrCode.ERR_OK){
                    String code = intent.getStringExtra(WXEntryActivity.WECHAT_BIND_RESULT_CODE);
                    if(code == null) {
                        ToasUtil.toast(UserSettingActivity.this, "抱歉，认证出错，请稍后重试");
                        loading.cancel();
                        return;
                    }
                    String appId = "wx73bea73b9ead58e8";
                    String secret = "9db2a5dda3f0ca977859cc9ad414a0b8";
                    String grant_type = "authorization_code";
                    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                            + "appId=" + appId
                            + "&secret=" + secret
                            + "&code=" + code
                            + "&grant_type=" + grant_type;
                    HttpGet.httpGetData(WEICHAT_ACCESS_TOKEN_CODE, url, UserSettingActivity.this);
                } else{
                    loading.cancel();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXEntryActivity.WECHAT_BIND);
        weChatLocalBroadcastManager.registerReceiver(weChatBroadcaseReciver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadCast);
        weChatLocalBroadcastManager.unregisterReceiver(weChatBroadcaseReciver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loading.cancel();
    }

    @Override
    public void finish() {
        if(settingUserDataModel.hasDataChange(userData))
            saveUserData();
        setResult(RESULT_OK);
        userData.setCompanyList(companysData);
        super.finish();
    }

    /* 绑定微信 */
    private void bindWeChat(){
        if (!api.isWXAppInstalled()){
            ToasUtil.toast(this, "抱歉，你还未安装微信，请先安装后重试");
        } else {
            loading.show();
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "weiChatLoginState";
            api.sendReq(req);
        }
    }

    /* 微信认证时 http get请求回调 */
    @Override
    public void onError(int requestCode, Throwable e) {
        loading.cancel();
        if(requestCode == WEICHAT_GET_USER_DATA){
            ToasUtil.toast(this, "抱歉，获取 access_token 失败，请稍后重试");
        } else if(requestCode == WEICHAT_GET_USER_DATA){
            ToasUtil.toast(this, "抱歉，获取微信个人信息失败，请稍后从重试");
        }
    }
    @Override
    public void onNext(int requestCode, String data) {
        if(requestCode == WEICHAT_ACCESS_TOKEN_CODE){
            try {
                JSONObject json = new JSONObject(data);
                String accessToken = json.getString("access_token");
                String openId = json.getString("openid");
                String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                        + accessToken + "&openid=" + openId;
                HttpGet.httpGetData(WEICHAT_GET_USER_DATA, url, this);
            } catch (JSONException e) {
                onError(requestCode, e);
            }
        } else if(requestCode == WEICHAT_GET_USER_DATA){
            ToasUtil.toast(this, "微信信息获取成功");
            SettingWeChatModel weiChatBindModel = JsonUtil.getInstance()
                    .jsonToObject(data, SettingWeChatModel.class);
            /* 设置微信信息 */
//            bindWeChatView.setVisibility(View.GONE);
//            weChatHadView.setVisibility(View.VISIBLE);
            bindWeChatRemindText.setText("已绑定微信\t");
            bindWeChatText.setText("重新绑定");
            settingUserDataModel.setOpenid(weiChatBindModel.getOpenid());
            settingUserDataModel.setNickname(weiChatBindModel.getNickname());
            settingUserDataModel.setGender(weiChatBindModel.getSex() == 1 ? "男" : "女");
            settingUserDataModel.setPortrait(weiChatBindModel.getHeadimgurl());
            if(userData.getPortrait() == null || userData.getPortrait().trim().length() == 0) {
                userData.setNickname(settingUserDataModel.getNickname());
                userData.setGender(settingUserDataModel.getGender());
                userData.setPortrait(settingUserDataModel.getPortrait());
                nicknameDesc.setText(settingUserDataModel.getNickname());
                sexDesc.setText(settingUserDataModel.getGender());
                ImageLoadUtil.loadCircle(this, settingUserDataModel.getPortrait(), headIcon);
            }
            /* 提交微信信息 */
            JsonObject param = new JsonObject();
            param.addProperty("token", HttpHelper.token);
            param.addProperty("nickname", weiChatBindModel.getNickname());
            param.addProperty("gender", weiChatBindModel.getSex());
            param.addProperty("portrait", weiChatBindModel.getHeadimgurl());
            param.addProperty("province", weiChatBindModel.getProvince());
            param.addProperty("city", weiChatBindModel.getCity());
            param.addProperty("country", weiChatBindModel.getCountry());
            param.addProperty("openid", weiChatBindModel.getOpenid());
            param.addProperty("unionid", weiChatBindModel.getUnionid());
            param.addProperty("op", true);
            HttpHelper.getInstance(this).bindWeiChat(param, WEICHAT_DATA_COMMIT_CODE, this);
        }
    }
}
